#include "videocall.h"
#include "ui_videocall.h"

#include <QMessageBox>

VideoCall::VideoCall(const QString _pushUrl, const QString _pullUrl, QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::VideoCall)
    , pullUrl(_pullUrl)
    , pushUrl(_pushUrl)
{
    ui->setupUi(this);

    QString url = "rtmp://116.198.241.238:8890/live/" + pushUrl;
    qDebug() << "--------------------------------推流推流" << url;

    try {
        vp = new VideoPush(this);
    } catch (const std::runtime_error& e) {
        QMessageBox::question(NULL, "推流失败", e.what());
        vp = nullptr;
        return;
    }

    connect(vp, &VideoPush::finished, this, [this]{
        vp->deleteLater();
        vp = nullptr;
        qDebug() << "释放推流";
    });

    vp->set_encoder(url.toStdString().c_str());
    vp->start();
}

VideoCall::~VideoCall()
{
    delete ui;
    qDebug() << "aaaa";
}

void VideoCall::start_pull()
{
    ui->label->setStyleSheet("background-color: rgb(0, 0, 0);");
    QString url = "rtmp://116.198.241.238:8890/live/" + pullUrl;
    qDebug() << "-----------------------------拉流拉流" << url;

    //拉流等待时不能关闭
    vps = new VideoPullStream(url);
    connect(vps, &VideoPullStream::frameReady, this, [this](const QImage& img){
        QPixmap pixmap = QPixmap::fromImage(img);
        if (!b) ui->pushButton_3->setIcon(pixmap);
        else ui->label->setPixmap(pixmap);
        ui->label->repaint();//刷新
    });
    connect(vps, &VideoPullStream::finished, this, [this]{
        vps->deleteLater();
        vps = nullptr;
        qDebug() << "释放拉流";
    });

    vps->start();
}

void VideoCall::on_pushButton_clicked()
{
    start_pull();
    // vp->stop_push();
}

void VideoCall::on_pushButton_3_clicked()
{
    b = !b;
}

void VideoCall::closeEvent(QCloseEvent * event)
{
    if(vp) vp->stop_push();
    if(vps) vps->stop_pull();
    QWidget::closeEvent(event);
    deleteLater();
}

